package com.junsi.controller;

import com.junsi.bean.Approve;
import com.junsi.bean.ApproveRole;
import com.junsi.bean.ApproveTail;
import com.junsi.bean.ContractApprove;
import com.junsi.bean.Rank;
import com.junsi.bean.Salestage;
import com.junsi.bean.Staff;
import com.junsi.service.ApproveRoleService;
import com.junsi.service.ApproveService;
import com.junsi.service.ApproveTailService;
import com.junsi.service.ContractApproveService;
import com.junsi.service.RankService;
import com.junsi.service.SalestageService;
import com.junsi.service.StaffSerivce;
import com.junsi.util.DownlaodExcel;
import com.junsi.util.DownloadUtil;
import com.junsi.util.FileUtil;
/**
 * 开户审批
 */
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/contractApprove")
public class ContractApproveController {
	@Autowired
	private ContractApproveService contractApproveService;
	@Autowired
	private ApproveService approveService;
	@Autowired
	private ApproveTailService apperoveTailService;
	@Autowired
	private ApproveRoleService approveRoleService;
	@Autowired
	private RankService rankService;
	@Autowired
	private ApproveTailService approveTailService;
	@Autowired
	private SalestageService salestageService;
	@Autowired
	private StaffSerivce staffSerivce;
	Logger logger = Logger.getRootLogger();

	@RequestMapping("/download") // 文件下载
	public void download(String id, String vlaues, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		Approve approve = approveService.findById(Integer.valueOf(id));
		ContractApprove contractApprove = contractApproveService
				.findById(Integer.valueOf(approve.getAcontractApproveId()));
		if ("0".equals(vlaues)) {// 营业执照图片
			DownloadUtil.download(contractApprove.getbLicenseimage(), response, request);
		} else if ("1".equals(vlaues)) {// 身份证正面
			DownloadUtil.download(contractApprove.getIdentityFront(), response, request);
		} else if ("2".equals(vlaues)) {// 身份证反面
			DownloadUtil.download(contractApprove.getIdentityReverse(), response, request);
		} else if ("3".equals(vlaues)) {// 文件上传
			DownloadUtil.download(contractApprove.getFileUploading(), response, request);
		}

	}

	@RequestMapping("/insert")//approveCharacter
	public ModelAndView insert(ContractApprove contractApprove, String apperoveTail, String applyNatureOne,
			HttpServletResponse response, HttpServletRequest request, String approveCharacter,
			@RequestParam("bLicenseimageFile") CommonsMultipartFile bLicenseimageFile,
			@RequestParam("identityFrontFile") CommonsMultipartFile identityFrontFile,
			@RequestParam("identityReverseFile") CommonsMultipartFile identityReverseFile,
			@RequestParam("fileUploadingFile") CommonsMultipartFile fileUploadingFile) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		boolean result = false;
		boolean r = false;
		if (apperoveTail != null && !"".equals(apperoveTail)) {
			if (!bLicenseimageFile.isEmpty()) {// 营业执照图片
				String picture1 = FileUtil.Uploadfile(bLicenseimageFile);
				if ("上传失败".equals(picture1)) {
					modelAndView.addObject("reult", "营业执照图片上传失败");
					modelAndView.setViewName("forward:/page/pacts.jsp");
					return modelAndView;
				}
				contractApprove.setbLicenseimage(picture1);
			}
			if (!identityFrontFile.isEmpty()) {// 身份证正面
				String picture1 = FileUtil.Uploadfile(identityFrontFile);
				if ("上传失败".equals(picture1)) {
					modelAndView.addObject("reult", "身份证正面上传失败");
					modelAndView.setViewName("forward:/page/pacts.jsp");
					return modelAndView;
				}
				contractApprove.setIdentityFront(picture1);
			}
			if (!identityReverseFile.isEmpty()) {// 身份证反面
				String picture1 = FileUtil.Uploadfile(identityReverseFile);
				if ("上传失败".equals(picture1)) {
					modelAndView.addObject("reult", "身份证反面上传失败");
					modelAndView.setViewName("forward:/page/pacts.jsp");
					return modelAndView;
				}
				contractApprove.setIdentityReverse(picture1);

			}
			if (!fileUploadingFile.isEmpty()) {// 文件上传
				String picture1 = FileUtil.Uploadfile(fileUploadingFile);
				if ("上传失败".equals(picture1)) {
					modelAndView.addObject("reult", "文件上传上传失败");
					modelAndView.setViewName("forward:/page/pacts.jsp");
					return modelAndView;
				}
				contractApprove.setFileUploading(picture1);
			} else {
				contractApprove.setFileUploading("没有文件");
			}
			if (applyNatureOne == null || "".equals(applyNatureOne)) {
				modelAndView.addObject("show", "申请性质为空!");
				modelAndView.setViewName("forward:/page/pacts.jsp");
				return modelAndView;
			}
			Rank rank = rankService.findById(Integer.valueOf(applyNatureOne));
			contractApprove.setApplyNature(rank.getRankName());
			ApproveTail approveTails = new ApproveTail();
			ApproveRole approveRole = approveRoleService.findById(Integer.valueOf(apperoveTail));
			approveTails.setApproverID(approveRole.getApprover());
			approveTails.setApproveType(approveRole.getTypeObject());
			approveTails.setApproveRoleId(approveRole.getApproveRoleId().toString());
			apperoveTailService.insert(approveTails);
			if (approveCharacter != null && !"".equals(approveCharacter.trim())) {
				List<Staff> staffs = staffSerivce.findByAll();// 管理员填写审批表
				for (Staff s : staffs) {
					String id = s.getStaff_id().toString();
					if (id.equals(approveCharacter)) {
						contractApprove.setUsername(s.getStaff_name());
					}
				}

			} else {
				Staff staff = ((Staff) request.getSession().getAttribute("staff"));
				contractApprove.setUsername(staff.getStaff_name());
			}
			contractApprove.setApprovalState("待审批");
			List<Approve> approve = new ArrayList<Approve>();
			ApproveTail approveTail = (ApproveTail) this.apperoveTailService.findById(approveTails.getApproveId());// 审批跟踪id
			contractApprove.setApproveType(approveTail.getApproveType());
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date date = new Date();
			String saleStageTime = simpleDateFormat.format(date);
			contractApprove.setSaleStageName(saleStageTime);
			result = this.contractApproveService.insert(contractApprove);
			if ((approveTail.getApproverId() != null) || ("".equals(approveTail.getApproverId()))) {
				String[] array = approveTail.getApproverId().split(",");
				for (int i = 0; i < array.length; i++) {
					Approve a = new Approve();
					a.setSenderId(contractApprove.getUsername());
					a.setApproverID(array[i]);
					a.setApproveCondition("未批准");
					a.setApproveRoleId(approveTails.getApproveId().toString());// 审批跟踪id
					a.setAcontractApproveId(contractApprove.getContractApproveId().toString());
					approve.add(i, a);
				}
			}
			r = this.approveService.batchSave(approve);
			if ((result) && (r)) {
				modelAndView.addObject("show", "开户审批提交成功!");
			} else {
				modelAndView.addObject("show", "开户审批提交失败!");
			}
		} else {
			modelAndView.addObject("show", "审批部门不可为空");
		}
		modelAndView.setViewName("forward:/approve/count.action?pageSize=0");
		return modelAndView;
	}

	@RequestMapping("/submitContract") // 审批
	public ModelAndView submitContract(Approve approve, HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		boolean result = false;
		if (approve.getApproveid() != null) {
			this.approveService.updateRemarks(approve);
			Approve approveData = (Approve) this.approveService.findById(approve.getApproveid());
			ApproveTail approveTail = this.apperoveTailService.findapprove(approveData.getApproveRoleId());
			String r = approve.getApproveCondition();
			String approver = null;
			Approve approve2 = new Approve();
			ContractApprove contractApprove2 = new ContractApprove();
			ApproveTail approveTail2 = new ApproveTail();
			approveTail2.setApproveID(approveTail.getApproveId());
			approve2.setApproveRoleId(approveTail.getApproveId().toString());
			Integer contractApproveId = Integer.valueOf(approveData.getAcontractApproveId());
			contractApprove2.setContractApproveId(contractApproveId);
			if (r.equals("不批准")) {
				approve2.setApproveCondition("不批准");
				contractApprove2.setApprovalState("审批失败");
				this.approveService.batchUpdate(approve2);// 不批准
				approveTail2.setApproverID("");
				this.contractApproveService.update(contractApprove2);
				result = this.apperoveTailService.updateApproverID(approveTail2);

			}
			if (r.equals("已批准")) {
				String[] approverId = approveTail.getApproverId().split(",");
				if ((approverId.length == 1) && (!"".equals(approverId[0]))) {
					approve2.setApproveCondition("已批准");
					contractApprove2.setApprovalState("已批准");
					approveTail2.setApproverID("");
					approve2.setApproveid(approveData.getApproveid());
					this.approveService.update(approve2);
					this.contractApproveService.update(contractApprove2);
					approveTail2.setApproveID(approveTail.getApproveId());
					result = this.apperoveTailService.updateApproverID(approveTail2);
				}
				if (approverId.length == 2) {
					approver = approverId[1];
					approve2.setApproveCondition("已批准");
					contractApprove2.setApprovalState("审批中");
					approve2.setApproveid(approveData.getApproveid());
					this.approveService.update(approve2);
					approveTail2.setApproveID(approveTail.getApproveId());
					approveTail2.setApproverID(approver);
					approveTail2.setApproveID(approveTail.getApproveId());
					this.contractApproveService.update(contractApprove2);
					result = this.apperoveTailService.updateApproverID(approveTail2);
				} else if (approverId.length > 2) {
					for (int i = 1; i < approverId.length; i++) {
						if (i > 1) {
							approver = approver + "," + approverId[i];
						} else {
							approver = approverId[i];
						}
					}
					approve2.setApproveCondition("已批准");
					contractApprove2.setApprovalState("审批中");
					approve2.setApproveid(approveData.getApproveid());
					this.approveService.update(approve2);
					approveTail2.setApproveID(approveTail.getApproveId());
					approveTail2.setApproverID(approver);
					this.contractApproveService.update(contractApprove2);
					result = this.apperoveTailService.updateApproverID(approveTail2);
				}

			}
		}
		ModelAndView modelAndView = new ModelAndView();
		if (result) {
			modelAndView.addObject("show", "审批成功!");
		} else {
			modelAndView.addObject("show", "审批失败!");
		}
		modelAndView.setViewName("forward:/approve/count.action");
		return modelAndView;
	}

	/**
	 * 更新
	 */
	@RequestMapping("/update")
	public ModelAndView update(ContractApprove contractApprove) {
		ModelAndView modelAndView = new ModelAndView();
		if (contractApprove.getContractApproveId() == null) {
			modelAndView.setViewName("forward:/approve/count.action?pageSize=2");
			return modelAndView;
		}
		boolean r = contractApproveService.updateAll(contractApprove);
		if (!r) {
			modelAndView.addObject("show", "更新失败!");
			logger.error("开户审批更新失败!");
		} else {
			modelAndView.addObject("show", "更新成功!");
		}
		modelAndView.setViewName("forward:/approve/count.action?pageSize=2");
		return modelAndView;
	}

	/**
	 * 删除 id:审批表ID
	 */
	@RequestMapping("/delect")
	public ModelAndView delect(String id,String pageNums) {
		ModelAndView modelAndView = new ModelAndView();
		Approve approve = approveService.findById(Integer.valueOf(id));
		ApproveTail approveTail = approveTailService.findById(Integer.valueOf(approve.getApproveRoleId()));
		if (approveTail.getApproverId() != null && !"".equals(approveTail.getApproverId())) {
			String[] approverid = approveTail.getApproverId().split(",");
			String approveridArray = "";
			for (int i = 0; i < approverid.length; i++) {
				if (!approverid[i].equals(approve.getApproverID())) {
					if ("".equals(approveridArray)) {
						approveridArray = approverid[i];
					} else {
						approveridArray += "," + approverid[i];
					}
				}
			}
			approveTail.setApproverID(approveridArray);
			try {
				approveTailService.update(approveTail);
			} catch (Exception e) {
				logger.error("ContractApproveController----------------->>delect:update出错");
				e.printStackTrace();
			}
		} else {
			int sun = approveService.findAppoveContractSun(approve.getAcontractApproveId());
			if (sun <= 1) {
				contractApproveService.delete(Integer.valueOf(approve.getAcontractApproveId()));
			}
		}
		boolean r = approveService.delete(Integer.valueOf(id));
		if (!r) {
			modelAndView.addObject("show", "删除失败!");
			logger.error("开户审批删除失败!");
		} else {
			modelAndView.addObject("show", "删除成功!");
		}
		modelAndView.setViewName("forward:/approve/count.action?pageSize=2&pageNum="+pageNums);
		return modelAndView;
	}

	/**
	 * 导出
	 */
	@RequestMapping("/downlaodExecls")
	public void downlaodExecls(HttpServletResponse response) {
		List<ContractApprove> contractApproves = contractApproveService.listAll();
		for (ContractApprove contractApprove2 : contractApproves) {
			List<Salestage> salestages = salestageService.listAll();
			for (Salestage arraySalestage : salestages) {
				String salestage = arraySalestage.getSaleStageId().toString();
				if (salestage.equals(contractApprove2.getpCategory())) {
					contractApprove2.setpCategory(arraySalestage.getSaleStageName());
				}
			}
		}
		String headers[] = { "ApplyNature", "pCategory", "Cooperator", "rPerson", "ContractId", "ContractRate",
				"ContractTime", "WorkLocation", "ContractContent", "Deposit", "ClientelePhone", "ServiceQQ", "Imanager",
				"ActivateTime" };
		List<String> list1 = new ArrayList<String>();
		List<String> list2 = new ArrayList<String>();
		List<String> list3 = new ArrayList<String>();
		List<String> list4 = new ArrayList<String>();
		List<String> list6 = new ArrayList<String>();
		List<String> list8 = new ArrayList<String>();
		List<String> list9 = new ArrayList<String>();
		List<String> list10 = new ArrayList<String>();
		List<String> list11 = new ArrayList<String>();
		List<String> list12 = new ArrayList<String>();
		List<String> list13 = new ArrayList<String>();
		List<String> list14 = new ArrayList<String>();
		List<String> list15 = new ArrayList<String>();
		List<String> list16 = new ArrayList<String>();
		list1.add("申请性质");
		list2.add("产品类别");
		list3.add("合作单位");
		list4.add("负责人");
		list6.add("合同编号");
		list8.add("合约比例");
		list9.add("合同期限");
		list10.add("现办公地址");
		list11.add("合同内容");
		list12.add("保证金");
		list13.add("客户电话");
		list14.add("客服QQ");
		list15.add("招商经理");
		list16.add("激活时间");
		Map<String, Object> headerMap = new LinkedHashMap<String, Object>();
		headerMap.put("申请性质", list1);
		headerMap.put("产品类别", list1);
		headerMap.put("合作单位", list1);
		headerMap.put("负责人", list1);
		headerMap.put("合同编号", list1);
		headerMap.put("合约比例", list1);
		headerMap.put("合同期限", list1);
		headerMap.put("现办公地址", list1);
		headerMap.put("合同内容", list1);
		headerMap.put("保证金", list1);
		headerMap.put("客户电话", list1);
		headerMap.put("客服QQ", list1);
		headerMap.put("招商经理", list1);
		headerMap.put("追踪情况", list1);
		headerMap.put("激活时间", list1);
		DownlaodExcel.excel(response, contractApproves, "开户审批详情表", headerMap, headers);
	}
}